package tcpsend

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"strings"
)

const endLine byte = '\n'

type TcpSender struct {
	Conn        *net.Conn
	Keep        bool
	SendMessage chan []string
	GetMessage  chan string
	Stop        bool
}

func Start(addr string, keep bool, showLog bool, f func(string)) *TcpSender {
	t := &TcpSender{Keep: keep, SendMessage: make(chan []string, 1000), GetMessage: make(chan string, 1000)}
	go func() {
		for !t.Stop {
			f(<-t.GetMessage)
		}
	}()
	go func() {
		for !t.Stop {
			if keep {
				conn, err := net.Dial("tcp", addr)
				if err != nil {
					log.Printf("connect :%s error!\n", addr)
				} else {
					t.Conn = &conn
					if showLog {
						log.Printf(">>keep:%v connect :%s successful!\n", keep, addr)
					}
					for !t.Stop {
						for _, msg := range <-t.SendMessage {
							fmt.Fprintf(conn, string(append([]byte(msg), endLine)))
							msg, err := bufio.NewReader(conn).ReadString(endLine)

							if err != nil {
								break
							} else {
								t.GetMessage <- strings.TrimSpace(msg)
							}
						}
					}
				}
			} else {
				for _, msg := range <-t.SendMessage {
					conn, err := net.Dial("tcp", addr)
					if err != nil {
						log.Printf("connect :%s error!\n", addr)
					} else {
						if showLog {
							log.Printf("##keep:%v connect :%s successful!\n", keep, addr)
						}
						fmt.Fprintf(conn, string(append([]byte(msg), endLine)))
						msg, err := bufio.NewReader(conn).ReadString(endLine)
						if err != nil {
							break
						} else {
							t.GetMessage <- strings.TrimSpace(msg)
						}
					}
				}
			}
		}
	}()

	return t
}
